<template>
  <div class="barChart">
    <div
      id="consumptionBar"
      class="echart"
      :style="'height:' + height + 'px'"
    ></div>
  </div>
</template>

<script>
import echarts from "@/utils/lib/echarts";
import { BarChart } from "echarts/charts";
import { DataZoomComponent } from "echarts/components"; // 平移缩放功能按需引入
import colorConst from "@/utils/custom-color.js";
echarts.use([BarChart, DataZoomComponent]);
export default {
  name: "barChart",
  props: {
    // 柱状图数据
    barData: {
      type: Array,
      default: [],
    },
    // x轴坐标数据
    xData: {
      type: Array,
      default: [],
    },
    dataZoom: {
      type: Array,
      default: [],
    },
    height: {
      type: Number,
      default: 200,
    },
  },
  data() {
    return {
      chart: null,
    };
  },
  watch: {
    barData(val) {
      if (val) {
        this.chartDes();
        this.barCharts(this.barData, this.xData, this.dataZoom);
      }
    },
  },
  mounted() {
    this.barCharts(this.barData, this.xData, this.dataZoom);
  },
  beforeDestroy() {
    this.chartDes();
  },
  methods: {
    chartDes() {
      if (!this.chart) {
        return;
      }
      this.chart.dispose();
      this.chart = null;
    },
    barCharts(barData, xData, dataZoom) {
      let nameArr = [];
      barData.forEach((element) => {
        nameArr.push(element.name);
      });
      let option = {
        color: colorConst.customColorarr,
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "shadow",
          },
        },
        legend: {
          data: nameArr,
        },
        grid: {
          left: "1%",
          right: "1%",
          bottom: "1%",
          top: "13%",
          containLabel: true,
        },
        xAxis: {
          type: "category",
          data: xData,
        },
        dataZoom: dataZoom,
        yAxis: {
          type: "value",
        },
        series: barData,
      };
      this.initChart("consumptionBar", option);
    },
    initChart(id, options) {
      this.chart = echarts.init(document.getElementById(id));
      this.chart.setOption(options);
      window.addEventListener("resize", () => {
           if (this.chart) {
          this.chart.resize();
        }
      });
    },
  },
};
</script>

<style scoped lang="scss">
.barChart {
  .echart {
    width: 100%;
    height: 200px;
  }
}
</style>
